/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cashmate.struts;

import com.cashmate.hibernate.dao.AppraisalDAO;
import com.cashmate.hibernate.dao.EmployeeDAO;
import com.cashmate.hibernate.dao.LoanapplicationDAO;
import com.cashmate.hibernate.dao.LoanverificationDAO;
import com.cashmate.hibernate.pojo.Appraisal;
import com.cashmate.hibernate.pojo.Collaterals;
import com.cashmate.hibernate.pojo.Documents;
import com.cashmate.hibernate.pojo.Loanverification;
import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author Lee
 */
public class AddAppraisal extends ActionSupport implements ServletRequestAware {

    private Appraisal appr;
    private String actionstatus;
    private AppraisalDAO ad = (AppraisalDAO) ServletActionContext.getServletContext().getAttribute("appraisalDAO");
    private LoanapplicationDAO lad = (LoanapplicationDAO) ServletActionContext.getServletContext().getAttribute("loanapplicationDAO");
    private EmployeeDAO emd = (EmployeeDAO) ServletActionContext.getServletContext().getAttribute("employeeDAO");
    private LoanverificationDAO lvd = (LoanverificationDAO) ServletActionContext.getServletContext().getAttribute("loanverificationDAO");
    //loanapp
    private String loanverid;
    //appraisal
    private String accountnoapp, dateoffirstrelease, totalfairmarketvalue, totalappraisedvalue, loanableamount, employeeid;
    //document
    private String documentdateapp, docreftypeapp, docrefnoapp, docnoapp, doctypeapp;
    //collaterals
    private String[] makeandtype, brand, serialno, modelno, regcertno, motorno, chasisno, plateno, fairmarketvalue, location, gencon;
    private String successurl;
    //image
    private File userImage;
    private String userImageContentType;
    private String userImageFileName;
    private HttpServletRequest servletRequest;

    public String getSuccessurl() {
        return successurl;
    }

    public String getActionstatus() {
        return actionstatus;
    }

    public void setActionstatus(String actionstatus) {
        this.actionstatus = actionstatus;
    }

    public void setAccountnoapp(String accountnoapp) {
        this.accountnoapp = accountnoapp;
    }

    public void setAppr(Appraisal appr) {
        this.appr = appr;
    }

    public void setDateoffirstrelease(String dateoffirstrelease) {
        this.dateoffirstrelease = dateoffirstrelease;
    }

    public void setDocnoapp(String docnoapp) {
        this.docnoapp = docnoapp;
    }

    public void setDocrefnoapp(String docrefnoapp) {
        this.docrefnoapp = docrefnoapp;
    }

    public void setDocreftypeapp(String docreftypeapp) {
        this.docreftypeapp = docreftypeapp;
    }

    public void setDoctypeapp(String doctypeapp) {
        this.doctypeapp = doctypeapp;
    }

    public void setBrand(String[] brand) {
        this.brand = brand;
    }

    public void setChasisno(String[] chasisno) {
        this.chasisno = chasisno;
    }

    public void setFairmarketvalue(String[] fairmarketvalue) {
        this.fairmarketvalue = fairmarketvalue;
    }

    public void setGencon(String[] gencon) {
        this.gencon = gencon;
    }

    public void setLocation(String[] location) {
        this.location = location;
    }

    public void setMakeandtype(String[] makeandtype) {
        this.makeandtype = makeandtype;
    }

    public void setModelno(String[] modelno) {
        this.modelno = modelno;
    }

    public void setMotorno(String[] motorno) {
        this.motorno = motorno;
    }

    public void setPlateno(String[] plateno) {
        this.plateno = plateno;
    }

    public void setRegcertno(String[] regcertno) {
        this.regcertno = regcertno;
    }

    public void setSerialno(String[] serialno) {
        this.serialno = serialno;
    }

    public void setDocumentdateapp(String documentdateapp) {
        this.documentdateapp = documentdateapp;
    }

    public void setLoanableamount(String loanableamount) {
        this.loanableamount = loanableamount;
    }

    public void setLoanverid(String loanverid) {
        this.loanverid = loanverid;
    }

    public void setTotalappraisedvalue(String totalappraisedvalue) {
        this.totalappraisedvalue = totalappraisedvalue;
    }

    public void setTotalfairmarketvalue(String totalfairmarketvalue) {
        this.totalfairmarketvalue = totalfairmarketvalue;
    }

    public File getUserImage() {
        return userImage;
    }

    public void setUserImage(File userImage) {
        this.userImage = userImage;
    }

    public String getUserImageContentType() {
        return userImageContentType;
    }

    public void setUserImageContentType(String userImageContentType) {
        this.userImageContentType = userImageContentType;
    }

    public String getUserImageFileName() {
        return userImageFileName;
    }

    public void setUserImageFileName(String userImageFileName) {
        this.userImageFileName = userImageFileName;
    }

    @Override
    public void setServletRequest(HttpServletRequest servletRequest) {
        this.servletRequest = servletRequest;
    }

    @Action(value = "/add-appraisal", results = {
        @Result(name = "input", location = "${successurl}"),
        @Result(name = "success", location = "${successurl}"),
        @Result(name = "error", location = "${successurl}")
    })
    @Override
    public String execute() {
        successurl = "../../loanapplication.jsp?cat=appraise";
        List<Collaterals> listcol = new ArrayList<Collaterals>();
        Appraisal a = null;
//        Loanapplications l = null;
        Loanverification lv = null;
        Documents d = null;

        try {
            Integer.parseInt(loanverid);
//            Integer.parseInt(accountnoapp);
            Integer.parseInt(totalfairmarketvalue);
            Integer.parseInt(totalappraisedvalue);
            Integer.parseInt(loanableamount);
        } catch (Exception e) {
            e.printStackTrace();
            actionstatus = "A string value was provided for a textfield that expects a numeric value.";
            return INPUT;
        }

        d = new Documents(docnoapp, doctypeapp, documentdateapp, true);
        d.setFilename(userImageFileName);
//        l = lad.getById(Integer.parseInt(loanappidapp));
        try {
            lv = lvd.get(Integer.parseInt(loanverid));
        } catch (Exception e) {
            actionstatus = "Employee not found.";
            return INPUT;
        }
        a = new Appraisal(1, dateoffirstrelease, Integer.parseInt(totalfairmarketvalue), Integer.parseInt(totalappraisedvalue), Integer.parseInt(loanableamount), "saved");
        a.setDocuments(d);
        a.setLoanverifications(lv);
        try {
            a.setEmployees(emd.getByIdNumber(employeeid));
        } catch (Exception e) {
            actionstatus = "No employee was mapped with this appraisal.";
            return INPUT;
        }

        try {


            if (makeandtype.length != 0 && brand.length != 0 && serialno.length != 0 && modelno.length != 0 && gencon.length != 0) {
                for (int i = 0; i < makeandtype.length; i++) {
                    if (!makeandtype[i].equals("") && !brand[i].equals("") && !serialno[i].equals("") && !modelno[i].equals("") && !gencon[i].equals("")) {
                        try {
                            int fair = Integer.parseInt(fairmarketvalue[i]);
//                            Appraisal appraisal, String makeandtype, String brand, String serialno, String modelno, 
//                                    String regcertno, String motorno, String chasisno, String plateno, 
//                                            Integer fairmarketvalue, String location, String generalcondition

                            Collaterals c = new Collaterals(a, makeandtype[i], brand[i], serialno[i], modelno[i], regcertno[i], motorno[i], chasisno[i], plateno[i],
                                    fair, location[i], gencon[i]);
                            listcol.add(c);
                        } catch (Exception e) {
                            e.printStackTrace();
                            actionstatus = "Some values specified for appraisal are not valid";
                            return SUCCESS;
                        }

                    }
                }
            }
            ad.addAppraisal(d, a, listcol);
            lv.setWithap("y");
            actionstatus = "Appraisal Saved.";
            lvd.update(lv); 

        } catch (Exception f) {
            f.printStackTrace();
            actionstatus = "Error. Please check that all the valued you've specified are valid and try again.";
        }

        if (userImageFileName != null) {
            if (!userImageFileName.equals("")) {

                try {

                    String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
                    String s = ServletActionContext.getRequest().getRealPath("/");
                    String[] split = s.split("\\\\");
                    ArrayList<String> path = new ArrayList<String>();
                    StringBuffer sb = new StringBuffer();

                    for (int i = 0; i <= split.length - 3; i++) {
                        path.add(i + " " + split[i]);
                        sb.append(split[i]);

                        if (i != split.length - 3) {
                            sb.append("\\");
                        }
                    }

                    sb.append("\\web\\res\\documentimages\\appraisals");
                    String filePath1 = sb.toString();
//                    System.out.println(sb.toString());
//
//                    System.out.println("1: " + getClass().getClassLoader().getResource(".").getPath());
//                    System.out.println("2: " + ServletActionContext.getRequest().getContextPath());
//                    System.out.println("3: " + ServletActionContext.getRequest().getRealPath("/"));
//                    System.out.println("4: " + servletRequest.getContextPath());
                    File fileToCreate = new File(filePath, this.userImageFileName);
                    File fileToCreate1 = new File(filePath1, this.userImageFileName);

                    FileUtils.copyFile(this.userImage, fileToCreate1);
                    FileUtils.copyFile(this.userImage, fileToCreate);
                } catch (Exception g) {
                    g.printStackTrace();
                    addActionError(g.getMessage());

                    return INPUT;
                }

            }
        }



        return SUCCESS;
    }
}
